package com.yourname.xhs.dao;

import com.yourname.xhs.entity.User;
import com.yourname.xhs.util.DES;
import com.yourname.xhs.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

//import static com.yourname.xhs.util.DbUtil.conn;
import static com.yourname.xhs.util.DES.desDecript;
import static com.yourname.xhs.util.DES.desEncript;
import static com.yourname.xhs.util.DbUtil.getConnection;

public class UserDaoImpl implements UserDao{
    public static String originKey="12345678";//密钥
    public static String cipherText;//密文
    ResultSet rs=null;
    Connection conn=null;
    PreparedStatement ps= null;


    //插入用户
  public boolean insert(User user) throws Exception {
        boolean i;
          try{
          conn= getConnection();
          String sql="insert into user(user_nickname,user_password) values(?,?)";
          ps= conn.prepareStatement(sql);
          ps.setString(1, user.getUserName());
          //插入时加密
          cipherText = desEncript(user.getPassword(),originKey);
          ps.setString(2, cipherText);
          int line=ps.executeUpdate();
          if(line>0){
              user.setPassword(cipherText);
             i=true;
          }
          else {
              i=false;
          }
      } catch (ClassNotFoundException e) {

          e.printStackTrace();
          throw new RuntimeException(e);
      }finally {
        DbUtil.close(rs,ps,conn);
      }
      return i;
  }



    public User select(String username) throws Exception {
        User foundUser = new User();

        try {
            conn = getConnection();
            String sql = "SELECT * FROM user WHERE user_nickname = ?";

            if (username != null) {
                ps = conn.prepareStatement(sql);
                ps.setString(1, username);
                rs = ps.executeQuery();
                if (rs.next()) {
                    foundUser = new User(
                            rs.getInt("id"),
                            rs.getString("user_nickname"),
                            rs.getString("user_password"),
                            rs.getString("is_admin")
                    );
                }
            } else {
                throw new IllegalArgumentException("username parameter cannot be null");
            }
            return foundUser;
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("Error occurred while selecting user", e);
        } finally {
            DbUtil.close(rs, ps, conn);
        }


    }


//查看全部用户
    public List<User> selectAllUser() throws Exception {

        List<User> usersList = new ArrayList<>();
        StringBuilder sb=new StringBuilder();
        try{
            conn= getConnection();
            String sql="SELECT user_nickname,is_admin,id FROM user WHERE is_admin='user'";
            ps = conn.prepareStatement(sql);
            rs=  ps.executeQuery();
            while (rs.next()) {
                String nickname = rs.getString("user_nickname");
                String isAdmin = rs.getString("is_admin");
                int id=rs.getInt("id");
                User user = new User();
                user.setUserId(id);
                user.setUserName(nickname);
                user.setIsadmin(isAdmin);
                usersList.add(user);


            }
            return usersList;
        }

        finally {

            DbUtil.close(rs,ps,conn);
        }

    }


   //判断管理员
   public String isAdmin(User user) throws Exception {
       String isadmin=null;
       try{
           conn= getConnection();
           String sql="select *from user where is_admin=?";
           ps=conn.prepareStatement(sql);
           ps.setString(1, user.getIsadmin());
           rs=ps.executeQuery();
           if(rs.next()){
            isadmin=rs.getString("is_admin");
           }

       }catch (ClassNotFoundException e){
           e.printStackTrace();
           throw new RuntimeException(e);
       }
       catch (SQLException e){
           e.printStackTrace();
       }
       finally {

           DbUtil.close(rs,ps,conn);

       }
       return isadmin;
   }


   //修改个人信息
   public int modifyInfo (User user,String Username) throws Exception {
       int rowsAffected=0;

           conn= getConnection();
           String sql="update user set user_nickname=? where id =?";

               ps = conn.prepareStatement(sql);
               ps.setString(1,Username);
               ps.setInt(2,user.getUserId());
          
               rowsAffected = ps.executeUpdate();
               if (rowsAffected > 0) {
                   user.setUserName(Username);//username必须和原来不一样
               }
               else {
                   System.out.println("修改失败！");
               }



              DbUtil.close(rs,ps,conn);

               return rowsAffected;

   }

   //修改密码
    public boolean modifyPassword(User user) throws Exception {
        boolean i;
        try{
            conn= getConnection();
            String sql="update user set user_password=? where user_nickname=?";

                ps = conn.prepareStatement(sql);
                ps.setString(1, user.getPassword());
                ps.setString(2, user.getUserName());
                int row=ps.executeUpdate();

            if(row>0){
                i=true;
            }
            else{
                i=false;
            }

            return i;
        }
        finally {

            DbUtil.close(rs,ps,conn);

        }


    }
}
